﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using EngineOfEvermore.Common;
using System.Xml.Linq;
using Green.Logging;
using NUnit.Framework;

namespace EngineOfEvermore.Scene.Visual
{
	[XmlObjectSerializer( typeof( VisualComponentXmlSerializer ) )]
    [PerType]
    public sealed class VisualComponent : SceneObjectComponent
    {
        #region UpdateTask class
        class UpdateTask : Task
        {
            public UpdateTask( VisualComponent owner )
                : base( 1000 )
            {
                _owner = owner;
            }

            public override void Execute( LogicUpdateEventArgs e )
            {
                _owner._update( e );
            }

            VisualComponent _owner;
        }
        #endregion

        #region ChildCollection class
        public sealed class ChildCollection : NamedObjectCollection<VisualComponentChild>
        {
            VisualComponent _owner;

            internal ChildCollection( VisualComponent owner )
            {
                _owner = owner;
            }

            protected override void _onItemAdded( VisualComponentChild item )
            {
                item.OnAddToVisualComponent( _owner );

                foreach ( VisualComponentChild sibling in this )
                {
                    if ( sibling != item )
                    {
                        sibling.OnSiblingAdded( item );
                        item.OnSiblingAdded( sibling );
                    }
                }

                if ( _owner.Scene != null )
                {
                    VisualSubSystem vss = _owner.Scene.GetSubSystem<VisualSubSystem>();

                    vss.RegisterDrawable( item );
                }
            }

            protected override void _onItemRemoved( VisualComponentChild item )
            {
                if ( _owner.Scene != null )
                {
                    VisualSubSystem vss = _owner.Scene.GetSubSystem<VisualSubSystem>();

                    vss.UnregisterDrawable( item );
                }

                foreach ( VisualComponentChild sibling in this )
                {
                    if ( sibling != item )
                    {
                        item.OnSiblingRemoved( sibling );
                        sibling.OnSiblingRemoved( item );
                    }
                }

                item.OnRemoveFromVisualComponent( _owner );
            }
        }
        #endregion

        #region Variables
        Task _updateTask;
        ChildCollection _children;
        Vector2d _positionOffset;
        float _rotationOffset;
        #endregion

        #region Constructor
        public VisualComponent()
        {
            _updateTask = new UpdateTask( this );
            _children = new ChildCollection( this );
        }
        #endregion

        #region Properties
        public Vector2d PositionOffset
        {
            get { return _positionOffset; }
            set { _positionOffset = value; }
        }

        public float RotationOffset
        {
            get { return _rotationOffset; }
            set { _rotationOffset = value; }
        }

        public ChildCollection Children
        {
            get { return _children; }
        }

        public Vector2d WorldPosition
        {
            get 
            {
                return this.Owner != null ?
                    this.Owner.GetWorldPosition( this.PositionOffset ) :
                    this.PositionOffset;
            }
        }

        public float WorldRotation
        {
            get 
            { 
                return this.Owner != null ? 
                    this.Owner.Rotation + this.RotationOffset : 
                    this.RotationOffset; 
            }
        }
        #endregion

        #region EntityComponent Callbacks
        internal protected override void OnAddToScene( SceneGraph scene )
        {
            base.OnAddToScene( scene );

            VisualSubSystem vss = scene.GetSubSystem<VisualSubSystem>();

            foreach ( VisualComponentChild child in _children )
            {
                vss.RegisterDrawable( child );
            }

            scene.TimeContext.AddRepeatingTask( _updateTask );
        }

        internal protected override void OnRemoveFromScene( SceneGraph scene )
        {
            scene.TimeContext.RemoveRepeatingTask( _updateTask );

            VisualSubSystem vss = scene.GetSubSystem<VisualSubSystem>();

            foreach ( VisualComponentChild child in _children )
            {
                vss.UnregisterDrawable( child );
            }

            base.OnRemoveFromScene( scene );
        }
        #endregion

        #region Methods
        public Vector2d GetWorldPosition( Vector2d localPosition )
        {
            if ( this.Owner != null )
            {
                var thisPosition = this.Owner.GetWorldPosition( this.PositionOffset );

                localPosition.Rotate( this.Owner.Rotation + this.RotationOffset );

                return thisPosition + localPosition;
            }
            else
            {
                var thisPosition = this.PositionOffset;

                localPosition.Rotate( this.RotationOffset );

                return thisPosition + localPosition;
            }
        }

        public Vector2d GetLocalPosition( Vector2d worldPosition )
        {
            throw new NotImplementedException();
        }

        public override SceneObjectComponent Clone()
        {
            var clone = new VisualComponent();
            clone.PositionOffset = this.PositionOffset;
            clone.RotationOffset = this.RotationOffset;

            foreach ( var child in this.Children )
            {
                clone.Children.Add( child.Clone() );
            }

            return clone;
        }
        #endregion

        #region Private Methods
        void _update( LogicUpdateEventArgs e )
        {
            foreach ( VisualComponentChild child in _children )
            {
                if ( child.NeedsUpdate )
                {
                    child.Update( e );
                }
            }
        }
        #endregion
    }

    public class VisualComponentSerializer<BASE_CLASS>
    {
        private readonly Dictionary<XName, Func<BASE_CLASS, XElement>> _serializers =
            new Dictionary<XName, Func<BASE_CLASS, XElement>>();

        private readonly
            Dictionary<XName, Action<XElement, BASE_CLASS>> _deserializers =
                new Dictionary<XName, Action<XElement, BASE_CLASS>>();

        private readonly Dictionary<Type, XName> _typeToXmlName =
            new Dictionary<Type, XName>();

        private readonly Dictionary<XName, Func<BASE_CLASS, bool>> _typeChecker =
            new Dictionary<XName, Func<BASE_CLASS, bool>>();

        private readonly Dictionary<XName, Func<BASE_CLASS>> _factories =
            new Dictionary<XName, Func<BASE_CLASS>>();

        public void RegisterSerializer<T>( XName elementName,
            Func<BASE_CLASS, XElement> serializer )
            where T : BASE_CLASS, new()
        {
            Debug.Assert( elementName != null );
            Debug.Assert( serializer != null );

            _serializers.Add( elementName, serializer );

            _registerTypeToXmlNameMapping<T>( elementName );
        }

        public void RegisterDeserializer<T>( XName elementName,
            Action<XElement, BASE_CLASS> deserializer )
            where T : BASE_CLASS, new()
        {
            Debug.Assert( elementName != null );
            Debug.Assert( deserializer != null );

            _registerTypeToXmlNameMapping<T>( elementName );

            _deserializers.Add( elementName, deserializer );
        }

        private void _registerTypeToXmlNameMapping<T>( XName elementName )
            where T : BASE_CLASS, new()
        {
            if ( _typeToXmlName.ContainsKey( typeof( T ) ) )
            {
                Debug.Assert( _typeToXmlName[typeof( T )].Equals( elementName ) );
            }
            else
            {
                _typeToXmlName.Add( typeof( T ), elementName );
                _typeChecker.Add( elementName, component => ( component is T ) );
                _factories.Add( elementName, () => new T() );
            }
        }

        public XElement Serialize( BASE_CLASS component )
        {
            XName xmlName;

            if ( !_typeToXmlName.TryGetValue( component.GetType(), out xmlName ) )
            {
                throw new NotSupportedException( "No serializer registered for type: " +
                    component.GetType().FullName );
            }

            Func<BASE_CLASS, XElement> serializer;

            if ( _serializers.TryGetValue( xmlName, out serializer ) )
            {
                return serializer( component );
            }
            else
            {
                throw new NotSupportedException( "No serializer registered for type: " +
                    component.GetType().FullName );
            }
        }

        public BASE_CLASS Deserialize( XElement xmlElement,
            BASE_CLASS component )
        {
            Action<XElement, BASE_CLASS> deserializer;

            if ( _deserializers.TryGetValue( xmlElement.Name, out deserializer ) )
            {
                deserializer( xmlElement, component );

                Debug.Assert( _typeToXmlName[component.GetType()].Equals( xmlElement.Name ) );

                return component;
            }
            else
            {
                throw new NotSupportedException( "No serializer registered for type: " +
                    xmlElement );
            }
        }

        public bool HasSerializerFor<T>( XName elementName )
            where T : SceneObjectComponent
        {
            return _serializers.ContainsKey( elementName ) &&
                _typeToXmlName[typeof( T )].Equals( elementName );
        }

        public bool HasDeserializerFor<T>( XName elementName )
        {
            return _deserializers.ContainsKey( elementName ) &&
                 _typeToXmlName[typeof( T )].Equals( elementName );
        }

        public void Clear()
        {
            _serializers.Clear();
            _deserializers.Clear();
            _typeToXmlName.Clear();
            _typeChecker.Clear();
            _factories.Clear();
        }
    }
	
	public class VisualComponentXmlSerializer : IXmlObjectSerializer {
		private VisualComponent _obj;
		
		public Object Obj 
		{ 
			get {
				return (Object) _obj;
			}
			
			set {
				if (value is VisualComponent) {
					_obj = (VisualComponent) value; 
				} else {
					_obj = null;
				}
			}
		}
		
		public void getXml(XElement node, XmlSerialization serializer) 
		{
			serializer.getXmlFromProperties(_obj, node);	
			
			XElement children = new XElement("children");
			node.Add(children);
			foreach(VisualComponentChild c in _obj.Children) {
				serializer.getXmlFromObject(c, children);	
			}
			
		}
		
		
		public Object loadFromXml(XElement node, XmlSerialization serializer)
		{
			_obj = new VisualComponent();
			
			serializer.loadPropertiesFromXml(_obj, node);
			foreach(XElement child in node.Element("children").Nodes()) {
				_obj.Children.Add((VisualComponentChild) serializer.loadObjectFromXml(child));
			}
			
			return _obj;			
		}
	
	}

    #if ENGINE_OF_EVERMORE_ENABLE_UNIT_TESTS
    namespace Test
    {
        [TestFixture]
        public class VisualComponentTestFixture
        {
            [Test]
            public void TestGetWorldPositionAtCenterNoRotations()
            {
                var sceneObject = new SceneObject();
                var visualComponent = new VisualComponent();

                sceneObject.AddComponent( visualComponent );

                sceneObject.Position = new Vector2d( 10, 30 );
                visualComponent.PositionOffset = new Vector2d( 30, 35 );

                var expectedPosition = sceneObject.Position + visualComponent.PositionOffset;

                var worldPosition = visualComponent.GetWorldPosition( Vector2d.Zero );

                Assert.That( worldPosition.EpsilonEquals( expectedPosition ) );
            }

            [Test]
            public void TestGetWorldPositionAtCenterNoRotationsNoOwner()
            {
                var visualComponent = new VisualComponent();
                visualComponent.PositionOffset = new Vector2d( 30, 35 );

                var expectedPosition = visualComponent.PositionOffset;

                var worldPosition = visualComponent.GetWorldPosition( Vector2d.Zero );

                Assert.That( worldPosition.EpsilonEquals( expectedPosition ) );
            }

            [Test]
            public void TestGetWorldPositionWithOffsetNoRotations()
            {
                var sceneObject = new SceneObject();
                var visualComponent = new VisualComponent();

                sceneObject.AddComponent( visualComponent );

                sceneObject.Position = new Vector2d( 10, 30 );
                visualComponent.PositionOffset = new Vector2d( 30, 35 );

                var localPosition = new Vector2d( 20, 19 );

                var expectedPosition = sceneObject.Position + visualComponent.PositionOffset
                    + localPosition;

                var worldPosition = visualComponent.GetWorldPosition( localPosition );

                Assert.That( worldPosition.EpsilonEquals( expectedPosition ) );
            }

            [Test]
            public void TestGetWorldPositionWithOffsetSceneObjectRotated()
            {
                var sceneObject = new SceneObject();
                var visualComponent = new VisualComponent();

                sceneObject.AddComponent( visualComponent );

                sceneObject.Rotation = 70;
                sceneObject.Position = new Vector2d( 10, 30 );

                visualComponent.PositionOffset = new Vector2d( 30, 35 );

                var rotatedPositionOffset = visualComponent.PositionOffset
                    .RotatedBy( sceneObject.Rotation );
                
                var localPosition = new Vector2d( 20, 19 );

                var rotatedLocalPosition = localPosition.RotatedBy( sceneObject.Rotation );

                var expectedPosition = sceneObject.Position + rotatedPositionOffset 
                    + rotatedLocalPosition;

                var worldPosition = visualComponent.GetWorldPosition( localPosition );

                Assert.That( worldPosition.EpsilonEquals( expectedPosition ) );
            }

            [Test]
            public void TestGetWorldPositionWithOffsetVisualComponentRotated()
            {
                var sceneObject = new SceneObject();
                var visualComponent = new VisualComponent();

                sceneObject.AddComponent( visualComponent );

                sceneObject.Position = new Vector2d( 10, 30 );

                visualComponent.RotationOffset = 40;
                visualComponent.PositionOffset = new Vector2d( 30, 35 );

                var localPosition = new Vector2d( 20, 19 );

                var rotatedLocalPosition = localPosition
                    .RotatedBy( visualComponent.RotationOffset );

                var expectedPosition = sceneObject.Position + visualComponent.PositionOffset
                    + rotatedLocalPosition;

                var worldPosition = visualComponent.GetWorldPosition( localPosition );

                Assert.That( worldPosition.EpsilonEquals( expectedPosition ) );
            }

            [Test]
            public void TestGetWorldPositionWithOffsetVisualComponentRotatedNoOwner()
            {
                var visualComponent = new VisualComponent();

                visualComponent.RotationOffset = 40;
                visualComponent.PositionOffset = new Vector2d( 30, 35 );

                var localPosition = new Vector2d( 20, 19 );

                var rotatedLocalPosition = localPosition
                    .RotatedBy( visualComponent.RotationOffset );

                var expectedPosition = visualComponent.PositionOffset + rotatedLocalPosition;

                var worldPosition = visualComponent.GetWorldPosition( localPosition );

                Assert.That( worldPosition.EpsilonEquals( expectedPosition ) );
            }

            [Test]
            public void TestGetWorldPositionWithOffsetVisualComponentAndSceneObjectRotated()
            {
                var sceneObject = new SceneObject();
                var visualComponent = new VisualComponent();

                sceneObject.AddComponent( visualComponent );

                sceneObject.Rotation = 30;
                sceneObject.Position = new Vector2d( 10, 30 );

                visualComponent.RotationOffset = 40;
                visualComponent.PositionOffset = new Vector2d( 30, 35 );

                var rotatedVisualComponentOffset = visualComponent.PositionOffset
                    .RotatedBy( sceneObject.Rotation );

                var localPosition = new Vector2d( 20, 19 );
                
                var rotatedLocalPosition = localPosition
                    .RotatedBy( sceneObject.Rotation + visualComponent.RotationOffset );

                var expectedPosition = sceneObject.Position + rotatedVisualComponentOffset
                    + rotatedLocalPosition;

                var worldPosition = visualComponent.GetWorldPosition( localPosition );

                Assert.That( worldPosition.EpsilonEquals( expectedPosition ) );
            }
        }
    }
    #endif
}
